<%--
  Created by IntelliJ IDEA.
  User: ravi
  Date: 8/3/12
  Time: 6:55 PM
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--@elvariable id="actionBean" type="com.depo.quiggle.view.controller.ReceivableInvoiceAction"--%>
<%@ include file="/WEB-INF/jsp/include/taglibs.jsp" %>
<script type="text/javascript" src=" ${pageContext.request.contextPath}/js/rateTableForQGL.js" >
 	</script>	 
<script type="text/javascript">
var applyPaymentFlag = false;
var actualUserId = '${actionBean.userId}';
var jobId = ${actionBean.invoice.job.jobId};
var rateitemcount = 0;
var reqrtcodes = [];
        var agencies = [

            <c:forEach items="${actionBean.agencies}" var="agency" varStatus="agencyStatus">
            {
                value:"${agency.userId} ${agency.initials} ${agency.firstName} ${agency.lastName}",
                id: "${agency.userId}",
                initial: "${agency.initials}",
                firstName: "${agency.firstName}",
                lastName: "${agency.lastName}"
            }
            <c:if test="${!agencyStatus.last}">,</c:if>
            </c:forEach>
        ];
        var proofers = [

            <c:forEach items="${actionBean.proofers}" var="proofer" varStatus="prooferStatus">
            {
                value:"${proofer.userId} ${proofer.initials} ${proofer.firstName} ${proofer.lastName}",
                id: "${proofer.userId}",
                initial: "${proofer.initials}",
                firstName: "${proofer.firstName}",
                lastName: "${proofer.lastName}"
            }<c:if test="${!prooferStatus.last}">,</c:if>

            </c:forEach>
        ];

        var scopists = [

            <c:forEach items="${actionBean.scopists}" var="scopist" varStatus="scopistStatus">
            {
                value:"${scopist.userId} ${scopist.initials} ${scopist.firstName} ${scopist.lastName}",
                id: "${scopist.userId}",
                initial: "${scopist.initials}",
                firstName: "${scopist.firstName}",
                lastName: "${scopist.lastName}"
            }<c:if test="${!scopistStatus.last}">,</c:if>
            </c:forEach>
        ];
        var rateunits =[

                        <c:forEach items="${actionBean.ratePriceType}" var="rateunit" varStatus="rateunitsts">
                        { 
                            id: "${rateunit.id}",
                            type: "${rateunit.type}"
                        }<c:if test="${!rateunitsts.last}">,</c:if>
                        </c:forEach>
                        ];
             var perrateunits =[

                             <c:forEach items="${actionBean.ratUnitType}" var="rateunit" varStatus="rateunitsts">
                             { 
                                 id: "${rateunit.id}",
                                 type: "${rateunit.type}"
                             }<c:if test="${!rateunitsts.last}">,</c:if>
                             </c:forEach>
                             ];
        
  


  function callAjaxToCalculatePaymentAferJobSaving(jobId){
  	 $.ajaxSetup({
  		   jsonp: null,
  		   jsonpCallback: null
  		});

  	    $.ajax({
  		  type:'POST',
  		  url: 'qgl-log-detail-accounting.action?calculatePaymentForAJob',//name of action?name of method in action
  		  dataType: 'json',
  		  data: {jobId:jobId},
  			 
  		  success: function(result){
  			   
  			if(result!=null){
  				$("#receivableAmount"+jobId).html();
  				$("#receivableAmount"+jobId).html("$"+result.receivableAmount.toFixed(2));
  				$("#receivableAmount"+jobId).html();
  				$("#payableAmount"+jobId).html("$"+result.payableAmount.toFixed(2));
  				$("#prooferPayable"+jobId).html("$"+result.prooferPayable.toFixed(2));
  				$("#scopistPayable"+jobId).html("$"+result.scopistPayable.toFixed(2));
  				$("#netAmount"+jobId).html("$"+result.netAmount.toFixed(2));
  			}
  		 },
  		  error:function() { 
  			  
  		  }
  	});
  }  

  function getAllReimbursedServices(jobId,id,type){
 	 $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});
		var value= document.getElementById(id).value;
		if(value == "false"){
			var reimid ='';
			  if(type == 'reim')
				  reimid = '#servicereimtext'+jobId;
			  else
				  reimid = '#servicenonreimtext'+jobId;
			  
			     $(reimid).html('No');
			return;
		}
		var reimid ='';
		 if(type == 'reim'){
			  reimid = '#servicereimtext'+jobId;
		 }else{
			  reimid = '#servicenonreimtext'+jobId;
		 }
		 $(reimid).html('<a href="javascript:{}" onclick="getAllReimbursedServices('+jobId+',\''+id+'\',\''+type+'\')">Yes</a>');
		 if($.trim($("#agencyId"+jobId).val()).length == 0 || $.trim($("#agencyId"+jobId).val()) =='0')
				return;
		 var newcodes={code:new Array()}
			getUserMasterRateItems(jobId,type,newcodes,$("#agencyId"+jobId).val(),false);
		 $.ajax({
		  type:'POST',
		  url: 'qgl-log-detail-accounting.action?getRateItemsFromJobService',
		  dataType: 'json',
		  data: {jobId:jobId,agencyId:$("#agencyId"+jobId).val(),type:type,typeId:$("#typeId"+jobId).val()},
			 
		  success: function(result){
			  rateitemcount = 0;
			  reqrtcodes = result[1];
			 $("#servicesreimforminner").html("");
			  var str = "<div id='allservicreimdiv'>";
			  str +='<div id="allservicreimErrorMSGdiv" class="fontStyle"></div>';
			  str += "<fieldset>";
		   	  str += "<table id='servreimberstable' style='width:100%;text-align: center;'>";
			  str += '<tbody><colgroup>';
			  str += '<col width="1%">';
              str += '<col width="9%">';
              str += '<col width="28%">';
              str += '<col width="7%">';
              str += '<col width="7%">';
              str += '<col width="8%">';
              str += '<col width="10%">';
              str += '<col width="9%">';
              str += '<col width="6%">';
              str += '<col width="6%">';
              str += '<col width="8%">';
	          str += '</colgroup>';
		   	str += "<th>Select</th>";
		   	str += "<th>Code</th>";
		   	str += "<th>Description</th>";
		   	str += "<th>Quantity</th>";
			str += "<th>Count</th>";
		   	str += "<th>Value</th>";
		   	str += "<th>Unit</th>";
		   	str += "<th>PerUnit</th>";
		   	str += "<th>Reimbursable<br>";
			str +="<input type='checkbox' class='checkboxAllReim-QGL' name='checkbox' value='checkbox' /></th>";
		   	str += "<th>Taxable<br>";
			str += "<input type='checkbox' class='checkboxAllTax-QGL' name='checkbox' value='checkbox' /></th>";
		    str += "<th></th>"; 
			str += "<tbody>"; 
			
            if(result != null && result[0].length > 0){
         	   for(var i in result[0]){
         		   str += getNewRateItemRow(result[0][i],'new',$("#typeId"+jobId).val(),jobId,$("#agencyId"+jobId).val());
         		   
         	   }
            }
            str += "</tbody>"; 
            str += " </table>";
            str += "</fieldset>";
            str +='<div id="allservicreimErrorMSGdivOuter" class="fontStyle"></div>';
            str += "</div>";
            $("#servicesreimforminner").html(str);
            //var buttons = "<input type='button' onclick='getRatesForReimbursment("+jobId+",\""+type+"\")' value='Click To Add From Rate Table'></input> ";
            //var buttons = "<input type='button' class='addNewRowItemClass' onclick='addNewRowItem(\""+type+"\")' value='Add New '></input> ";
           // buttons+= "<input type='button' onclick='getUserMasterRateItems("+jobId+",\""+type+"\")' value='Click To Add From Master Rate Table '></input> ";
            //$("#ratetableview").html(buttons);

            if(type == 'reim'){
	        	  
	        	   $('#servicesreimform').dialog( "option", "title", 'Services Reimbursed');


	           }else{
	        	  
	        	   $('#servicesreimform').dialog( "option", "title", 'Services Non-Reimbursed');


	           }
            
            $( "#servicesreimform").dialog({
                autoOpen: true,
                height: 450,
                width: 920,
                modal: true,
                open:function(){
					   $(".reimjobrateitemcode").live("change",function(){
							  var flag=ServhighlightDuplicates(".reimjobrateitemcode");
							  if (!flag){
							    serviceAutoPopulateMRItem($(this),type);
							  }
							});
					   $(".servdelete").live("click",function(){
					   	       //ServhighlightDuplicates(".reimjobrateitemcode");						 
							}); 
						$(".reimjobrateitemrateunit").live("change",function(){
						   if($(this).val()==2)
						   servicesReimexpedite(this);
						});	
						$(".reimjobrateitemperunit").live("focus",function(){
						 if($(this).closest("tr").find(".reimjobrateitemrateunit").val()==2)
						   	   servicesReimexpedite(this);
						});
						$(".reimjobrateitemperunit").closest("tbody").live("change",function(){
								servicesReimexpedite(".reimjobrateitemrateunit");
						
						});
					   },
                buttons: {
                	"Add New": function() {
              		   addNewRowItem(type);
                     },
              	   "Click To Add From Master Rate Table": function() {
              		    var codes={code:new Array()}
          		        $(".rateitemclass").each(function() { 
              		    if($("#jobrateitemid"+$(this).attr('id')).val() == '0' && $.trim($("#jobrateitemcode"+$(this).attr('id')).val()).length >0)
              		     {
              			   var obj1 = {};
              			   obj1["rateItemCode"] = $("#jobrateitemcode"+$(this).attr('id')).val();
              			   codes.code.push(obj1);
              		     }
              		  });
          		       getUserMasterRateItems(jobId,type,codes,$("#agencyId"+jobId).val(),true);
                     },
                     Cancel: function() {
                         $( this ).dialog( "close" );
                     },
                     "Apply Selected Code(s)": function() {
                 	   var reqVals = [];
                 	   $(".rateitemclass").each(function() {
                 		   reqVals.push($(this).attr('id'));
                 		});
                 	   var obj={
      	            			rateitems:new Array()
      	            			
      	            	}
      	            	obj["jobId"]=jobId;
                 	   obj["agencyId"]=$("#agencyId"+jobId).val();
						   var eFlag = false;
						   var str = '';
						   var ccval = '';
						   var actulPgs = '';
                 	  for(var k in reqVals){
                 		  var obj1 = {
	                			};
                 		  
                 		 var code = $.trim($("#jobrateitemcode"+reqVals[k]).val());
              		      if( (code == 'cc' || code == 'cC' || code == 'Cc' || code == 'CC') && $("#jobrateitemselected"+reqVals[k]).is(":checked")){
              			     ccval = $("#jobrateitemquantity"+reqVals[k]).val();
          			         actulPgs = $("#jobrateitemcount"+reqVals[k]).val();
              		      }
                 		  obj1["jobselected"] = $("#jobrateitemselected"+reqVals[k]).is(":checked"); 
                 		  obj1["rateItemId"] = $("#jobrateitemid"+reqVals[k]).val();
                 		  obj1["rateItemCode"] = ($("#jobrateitemcode"+reqVals[k]).val()).toUpperCase();
                 		  obj1["rateItemDesc"] = $("#jobrateitemdesc"+reqVals[k]).val();
                 		  obj1["quantity"] = $("#jobrateitemquantity"+reqVals[k]).val();
                 		  obj1["rateItemCount"] =  $("#jobrateitemcount"+reqVals[k]).val();
                 		  obj1["value"] =  $("#jobrateitemprice"+reqVals[k]).val();
                 		  obj1["rateItemrateunit"] = $("#jobrateitemrateunit"+reqVals[k]).val();
                 		  obj1["rateItemperunit"] =  $("#jobrateitemperunit"+reqVals[k]).val();
                 		  obj1["reimbursable"] =  $("#jobrateitemreimb"+reqVals[k]).is(":checked");
                 		  obj1["taxable"] = $("#jobrateitemtaxabl"+reqVals[k]).is(":checked"); 
                 		  obj1["newratecode"] = $("#jobrateitemperunit"+reqVals[k]).find("option:selected").text();	  
							  if($.trim(obj1["rateItemCode"]) == "")
							  {
								  str +='Code is Required.';
								  eFlag = true;
								 
							  }
							  if($.trim(obj1["rateItemCount"]) == "")
							  {
								  str +='Count is Required.';
								  eFlag = true;
							  }
							  if($.trim(obj1["quantity"]) == "")
							  {
								  str +='Quantity is Required.';
								  eFlag = true;
							  }
							  if($.trim(obj1["value"]) == "")
							  {
								str +='Value is Required.';
								eFlag = true;
							  }
							  else if(isNaN(obj1["value"]))
							  {
								  str +='Enter Numeric Value.';
								  eFlag = true;
						      }
							  $("#allservicreimErrorMSGdiv").html(str);
							  if(eFlag)
								  return;
							  
       	            	  obj.rateitems.push(obj1);
       	            	}  
                 	  $.ajaxSetup({
    	          		   jsonp: null,
    	          		   jsonpCallback: null
    	          		});

    	          	    $.ajax({
    	          		  type:'POST',
    	          		  url: 'qgl-log-detail-accounting.action?saveJobServices',
    	          		  dataType: 'json',
    	          		  data: {data:JSON.stringify(obj),type:type},
    	          			 
    	          		  success: function(result){
    	          			  
    	          			if(result.length == 0){
       	          				$("#servicesreimform").dialog( "close" );
       	          			if(ccval.length > 0){
   	          			    	$("#ccVal"+jobId).val(parseInt(ccval)+1);
   	          			        $("#ccValView"+jobId).html(parseInt(ccval)+1);
       	          			  }
       	          		     if($.trim(actulPgs).length > 0){
       	          		         $("#actulPgsView"+jobId).html(parseInt(actulPgs));
       	          		         $("#actulPgs"+jobId).val(parseInt(actulPgs));
       	          		     }
       	          			     saveSelectedJob(jobId,true);
       	          			}
       	          			  else{
       	          				$("#allservicreimErrorMSGdiv").html(result).addClass("errorblockdiv");
       	          			    $("#allservicreimErrorMSGdivOuter").html(result).addClass("errorblockdiv");
       	          			  }
    	          		 },
    	          		  error:function() { 
    	          			  
    	          		  }
    	          	});	
                 		  
                 		 // $( this ).dialog( "close" );
                    }
                },
                close: function() {

                }
            });
            
            
            
		 },
		  error:function() { 
		
		  }
	});

 }
</script>
<link rel="stylesheet" media="all" type="text/css" href="${pageContext.request.contextPath}/css/jquery/overcast/jquery-ui-1.8.21.custom.css" />
		<!--<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/css/my-profile.css" />-->

<%--<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/bcss/style.css" />--%>
<link type="text/css" rel="stylesheet"
	href="${pageContext.request.contextPath}/css/billing-invoice.css" />
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/css/qgl-log-pending.css" />
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/css/qgl-log-detail.css" />
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/css/qgl-dialog-buttons.css" />
<script type="text/javascript" src="${pageContext.request.contextPath}/js/qgl-log-detail-accounting.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/qgl-log-accounting.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/receivable-invoice.js"></script>

<%--<script type="text/javascript" src="${pageContext.request.contextPath}/bjs/custom.js"></script>--%>

<script type="text/javascript">
	$(document).ready(function() {
		ajaxCallToGetMasterRateItems(1);
    	ajaxCallToGetMasterRateItems(2);
		
		$("#helpContent").hide();
		$(function() {
			$("#close").click(function() {

				$("#helpContent").hide(500);

			});
			$("#slidebutton").click(function() {
				$("#helpContent").show(500);

			});

		});
		$(".detailsLink").click(function() {
			//$(".edit-job").trigger("click");
			$("#detailAccounting").toggle(500);

		});
		$("#applyPaymentLink").click(function () {
			 $("#applyPayment").toggle(500);
			 if(!applyPaymentFlag)
			{
			 applyPaymentFlag = true;
			 //$('.plainData').find(':input[value=""]:first').focus();
			 $('.plainData').find('#amount').focus();
			 $("html, body").animate({ scrollTop: $(document).height() }, 1000);
			}
			else
				applyPaymentFlag= false;
			
			
		});
		$("#printLink").click(function(){
		
		 	var DocumentContainer = document.getElementById('printInvoice');
			var WindowObject = window.open('', 'PrintWindow', 'width=950,height=750,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes');
			WindowObject.document.write("<style>#watermark{display:block;} #invoiceContainer .box {background: none repeat scroll 0 0 #FFFFFF;border: 1px solid #CCCCCC;clear: both; float: right;font: 12px/20px Tahoma,trebuchet ms;margin-bottom: 3px; margin-top: 0; padding: 0; text-align: left;   width: 270px;}#invoiceContainer .box .label {background: none repeat scroll 0 0 #F3F3F3;border-right: 1px solid #CCCCCC;display: inline-block;font-weight: bold;    margin-right: 5px; padding-left: 10px; padding-right: 10px; width: 100px;}.total {    font-size: 14px;}   .total .due { float: right; margin: 0 100px 0 0; padding: 0;    text-align: right;  width: 250px;}.bold {font-weight: bold;} .total .label {display: inline-block;float: left;margin: 0; padding: 0; text-align: right;width: 170px;}.plainData th {background: none repeat scroll 0 0 #EFEFEF; padding: 10px 5px;}.plainData td {padding: 5px;}.plainData {    background: none repeat scroll 0 0 #F8F8F8;border: 1px solid #CCCCCC;font: 12px tahoma,Helvetica,sans-serif;} #addressContainer { float: left; margin: 0;    padding: 0; width: 25%;}.clear {  clear: both;}address { color: #666666; font-size: 13px;    font-style: normal;} #invoiceContainer { float: right;    text-align: right; width: 70%;} body {font-family: Tahoma,serif;}</style>");
			WindowObject.document.writeln("<div style='width:98%'>");
			WindowObject.document.writeln(DocumentContainer.innerHTML);
			WindowObject.document.writeln("<input type='button' onclick='prints()' id='print' style='float:right;padding:5px;' value='print'></a>");
			WindowObject.document.writeln("</div>");
			WindowObject.document.writeln("<script>function prints(){document.getElementById('print').style.display ='none';print();window.close();}<\/script>");
			WindowObject.document.close();
		    WindowObject.focus();
		   // WindowObject.print();
		   // WindowObject.close();
		});
		/* $("#printLink").click(function(){
			$( "#billPreview" ).html($("#printInvoice").html());
			$( "#billPreview" ).dialog("open");			
		});
		
		 $( "#billPreview" ).dialog({
			 	title: "Invoice Accounts Receivable Preview",
		        autoOpen: false,
		        height: 500,
		        width: 860,
		        modal: true,
		        buttons: {
		            "Print": function() {
		            	window.print();
		            },		         
		            Cancel: function() {
		                $( this ).dialog( "close" );
		            }
		        }
		    }); */
	});
</script>

<style>
#masterTableInnerDiv select {width: 75px;}
.reimjobrateitemperunit {width: 75px;}
.reimjobrateitemrateunit {width: 75px;}
#applyPayment select:hover,#applyPayment input[type=text]:hover,#applyPayment select:focus,#applyPayment input[type=text]:focus{background:#FFF9B8;}
</style>